package com.example.VisualPassGuard;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class Run extends Activity {
    public static final boolean DEBUG = true;
    public static final String LOG_TAG = "VisualPassGuard";

    LinearLayout myGallery;

    int displayWidthPixels;
    int displayHeightPixels;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        displayWidthPixels = metrics.widthPixels;
        //displayHeightPixels = metrics.heightPixels;
        displayHeightPixels = Math.round((float) displayWidthPixels * 3 / 4);
        Log.i(Run.LOG_TAG, "widthPixels = " + displayWidthPixels);
        Log.i(Run.LOG_TAG, "heightPixels = " + displayHeightPixels);

        saveResourcesToInternalStorage("img1.png", R.drawable.wallpaper_1);
        saveResourcesToInternalStorage("img2.png", R.drawable.wallpaper_2);
        saveResourcesToInternalStorage("img3.png", R.drawable.wallpaper_3);

        myGallery = (LinearLayout) findViewById(R.id.mygallery);

        File file = new File(getBaseContext().getFilesDir() + "/" + "img1.png");
        myGallery.addView(insertPhoto(file.getAbsolutePath()));
        /*file = new File(getBaseContext().getFilesDir() + "/" + "img2.png");
        myGallery.addView(insertPhoto(file.getAbsolutePath()));
        file = new File(getBaseContext().getFilesDir() + "/" + "img3.png");
        myGallery.addView(insertPhoto(file.getAbsolutePath()));*/
    }

    View insertPhoto(String path) {
        Bitmap bm = decodeSampledBitmapFromUri(path, displayWidthPixels, displayHeightPixels);

        LinearLayout layout = new LinearLayout(getApplicationContext());
        layout.setLayoutParams(new LinearLayout.LayoutParams(displayWidthPixels + 10, displayHeightPixels + 10));
        layout.setGravity(Gravity.CENTER);

        ImageView imageView = new ImageView(getApplicationContext());
        imageView.setOnClickListener(new ImageClickListener());
        imageView.setLayoutParams(new ViewGroup.LayoutParams(displayWidthPixels, displayHeightPixels));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setImageBitmap(bm);

        layout.addView(imageView);
        return layout;
    }

    public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
        Bitmap bm = null;

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        bm = BitmapFactory.decodeFile(path, options);

        return bm;
    }

    public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }
        }

        return inSampleSize;
    }

    public void saveResourcesToInternalStorage(String fileName, int idOfRes) {
        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        try {
            fileOutputStream = getBaseContext().openFileOutput(fileName, Context.MODE_PRIVATE);
            inputStream = getBaseContext().getResources().openRawResource(idOfRes);

            int nRead;
            byte[] data = new byte[1024];

            while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                fileOutputStream.write(data, 0, nRead);
            }

            fileOutputStream.flush();

            if (DEBUG) Log.d(Run.LOG_TAG, ".saveResourcesToInternalStorage(" + fileName + ") OK");
        } catch (Exception e) {
            Log.e(Run.LOG_TAG, "saveResourcesToInternalStorage " + fileName + ". " + e.getMessage());
        } finally {
            try {
                if (fileOutputStream != null) fileOutputStream.close();
                if (inputStream != null) inputStream.close();
            } catch (Exception e) {
                Log.e(Run.LOG_TAG, "saveResourcesToInternalStorage " + fileName + ". " + e.getMessage());  //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }

    public boolean isInternalFileExist(String fileName) {
        File file = null;
        try {
            file = new File(getBaseContext().getFilesDir() + "/" + fileName);
            if (DEBUG) Log.d(Run.LOG_TAG, ".isInternalFileExist(" + fileName + ") " + file.exists());
        } catch (Exception e) {
            Log.e(Run.LOG_TAG, "isInternalFileExist " + fileName + ". " + e.getMessage());
            return false;
        }

        return file.exists();
    }

    private class ImageClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            /*Intent intent = new Intent(Run.this, ZoomInZoomOut.class);
            startActivity(intent);*/

            Intent intent = new Intent(Run.this, ZoomInZoomOut.class);
            startActivity(intent);
        }
    }
}
